<template>
  <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
    <!-- Tab栏 -->
    <a-tabs :active-key="defaultActiveKey" @change="handleChange" style="margin-top: 20px;">
      <a-tab-pane key="all" :tab="`全部（${dataSource.length} ）`"></a-tab-pane>
      <a-tab-pane key="selling" :tab="`待支付（${unpaidCount}）`"></a-tab-pane>
      <a-tab-pane key="alert" :tab="`待发货（${unfaitCount}）`"></a-tab-pane>
      <a-tab-pane key="warehouse" :tab="`待收货（${ungiveCount}）`"></a-tab-pane>
      <a-tab-pane key="lasthouse" :tab="`已完成（ ${unlastCount}）`"></a-tab-pane>
      <a-tab-pane key="exithouse" :tab="`已取消（ ${unfalseCount}）`"></a-tab-pane>
    </a-tabs>

    <a-table
        :columns="columns"
        :data-source="filteredDataSource"
        :pagination="pagination"
        row-key="id"
    >
      <!-- 商品信息列 -->
      <template slot="skuImage" slot-scope="text, record">
        <a-avatar :src="record.skuImage" shape="square" style="width: 50px; height: 50px;"/>
        <span>{{ record.goodsname }}</span>
      </template>

      <!-- 自定义 operate 列的内容 -->
      <template slot="operate" slot-scope="record">
        <!-- 订单详情按钮 -->
        <a-button type="link" @click="viewDetails(record.id)">
          订单详情
        </a-button>

        <!-- 发货按钮 -->
        <a-button v-if="record.orderStatus === '待发货'" type="link" @click="viewgoods(record)">
          去发货
        </a-button>
      </template>
    </a-table>

    <!-- 订单详情模态框 -->
    <a-modal
        v-model="isModalVisible"
        title="订单详情"
        @cancel="handleCancel"
        @ok="handleCancel"
        :width="800"
        class="order-details-modal"
    >
      <div class="order-details">
        <div class="order-image">
          <a-avatar :src="selectedOrder ? selectedOrder.skuImage : ''" shape="square"
                    style="width: 100px; height: 100px;"/>
        </div>
        <div class="order-info">
          <p><strong>订单编号：</strong><span>{{ selectedOrder ? selectedOrder.orderSn : '' }}</span></p>
          <p><strong>商品名称：</strong><span>{{ selectedOrder ? selectedOrder.goodsname : '' }}</span></p>
          <p><strong>收货人：</strong><span>{{ selectedOrder ? selectedOrder.addressContact : '' }}</span></p>
          <p><strong>支付金额：</strong><span>{{ selectedOrder ? selectedOrder.money : '' }}</span></p>
          <p><strong>支付状态：</strong><span>{{ selectedOrder ? selectedOrder.payIs : '' }}</span></p>
          <p><strong>订单状态：</strong><span>{{ selectedOrder ? selectedOrder.orderStatus : '' }}</span></p>
          <p><strong>订单备注：</strong><span>{{ selectedOrder ? selectedOrder.userRemark : '' }}</span></p>
        </div>
      </div>
    </a-modal>

    <!-- 发货模态框 -->
    <a-modal
        v-model="isShipModalVisible"
        title="发货"
        @cancel="handleShipCancel"
        @ok="shipqqOrder()"
        :width="800"
        class="ship-order-modal"
    >
      <div class="ship-order">
        <div class="order-info">
          <p><strong>订单编号：</strong><span>{{ selectedOrder ? selectedOrder.orderSn : '' }}</span></p>
          <p><strong>商品名称：</strong><span>{{ selectedOrder ? selectedOrder.goodsname : '' }}</span></p>
          <p><strong>收货人：</strong><span>{{ selectedOrder ? selectedOrder.addressContact : '' }}</span></p>
          <div v-if="defaultAddress" style="margin: 30px 0">
            <h3>默认地址信息</h3>
            <p><strong>收件人：</strong>{{ defaultAddress.contact }}</p>
            <p><strong>手机号：</strong>{{ defaultAddress.mobile }}</p>
            <p><strong>地址：</strong>{{ defaultAddress.provinceId }} {{ defaultAddress.cityId }}
              {{ defaultAddress.districtId }} {{ defaultAddress.info }}</p>
          </div>
          <a-form :model="shipForm">
            <a-form-item label="物流公司">
              <a-select v-model="selectedLogisticsCompany" placeholder="请选择物流公司" style="width: 100px">
                <a-select-option v-for="company in logisticsCompanies" :key="company" :value="company">
                  {{ company }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="物流单号">
              <a-input v-model="manualLogisticsCompany" placeholder="请输入物流单号"/>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </a-modal>

  </a-card>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      formState: {
        shoppid: "", // 编号
        shoppinfo: "", // 用户信息
        shoppsouse: "请选择", // 订单来源
        paywayf: "请选择", // 支付方式
        ddfours: "请选择", // 支付状态
        paydata: null, // 支付时间
      },

      defaultActiveKey: 'all', // 默认选中的Tab键
      dataSource: [], // 请求返回的数据
      filteredDataSource: [], // 用于存储过滤后的数据
      unpaidCount: 0, // 待支付数量
      unfaitCount: 0, // 待发货数量
      ungiveCount: 0, // 待收货数量
      unlastCount: 0, // 已完成数量
      unfalseCount: 0, // 已取消数量
      defaultAddress: {},
      logisticsCompanies: ['顺丰快递', '中通快递'], // 物流公司列表
      selectedLogisticsCompany: null,
      manualLogisticsCompany: '',//物流单号

      columns: [
        {title: '订单编号', dataIndex: 'orderSn', id: 'orderSn'},
        {title: '卖家昵称', dataIndex: 'username', name: 'username', id: 'id'},
        {title: '商品信息', dataIndex: 'skuImage', id: 'metrics', scopedSlots: {customRender: 'skuImage'}},
        {title: '实付金额', dataIndex: 'money', id: 'customer'},
        {title: '收货人', dataIndex: 'addressContact', id: 'addressContact'},
        {title: '支付状态', dataIndex: 'payIs'},
        {title: '订单状态', dataIndex: 'orderStatus'},
        {title: '操作', id: 'operate', scopedSlots: {customRender: 'operate'}}
      ],

      isModalVisible: false, // 控制订单详情模态框的显示
      isShipModalVisible: false, // 控制发货模态框的显示
      selectedOrder: null, // 保存选中的订单详情
      shipForm: { // 发货表单数据
        shippingCompany: '',
        trackingNumber: '',
      },

      pagination: {
        current: 1,  // 当前页
        pageSize: 10, // 每页显示的条数
        total: 0, // 总条数
        showSizeChanger: true, // 显示每页条数选择器
        showQuickJumper: true, // 显示跳转按钮
        onChange: this.handlePageChange, // 页码变化时的回调函数
      },
    };
  },
  mounted() {
    this.fetchOrderInfo();
    if (this.logisticsCompanies.length > 0) {
      this.selectedLogisticsCompany = this.logisticsCompanies[0]; // 默认选择第一个物流公司
    }
  },
  created() {
    this.filteredDataSource = [...this.dataSource]; // 初始化为所有数据
  },
  methods: {
    async fetchorderup(data) {
      try {
        // 发送POST请求
        const response = await axios.post(`${window.location.protocol}//${window.location.hostname}:8080/api/order/updateorderstatus`, data, {
          headers: {
            Authorization: `Bearer ` + localStorage.getItem('token'),  // 认证 token
          },
        });

        // 请求成功
        if (response.data.code === 200) {
          location.reload()

          // 关闭模态框
          this.isShipModalVisible = false;

        } else {
          this.$message.error('发货操作失败：' + response.data.msg);
        }
      } catch (error) {
        console.error('请求失败:', error);
        this.$message.error('发货操作失败，网络错误');
      }
    },

    viewgoods(record) {
      // 点击"发货"按钮时显示发货模态框
      this.selectedOrder = record;
      this.fetchUserAddressInfo()
      this.isShipModalVisible = true;
    },

    shipqqOrder() {
      // 准备要发送的数据
      const data = {
        ordersnid: this.selectedOrder.orderSn,  // 使用当前记录的单号
        status: 3,  //
        expressno: this.manualLogisticsCompany ? this.manualLogisticsCompany : '',  // 物流单号
        expressname: this.selectedLogisticsCompany ? this.selectedLogisticsCompany : '',  // 备注信息
      };
      this.fetchorderup(data)
    },

    async fetchUserAddressInfo() {
      try {
        const userId = this.selectedOrder.userId;
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/address/info?userId=${userId}`, {
          headers: {Authorization: `Bearer ` + localStorage.getItem('token')}
        });
        if (response.data.code === 200) {
          const addressData = response.data.data.reverse();
          console.log(addressData)
          this.defaultAddress = addressData.find(address => address.isDefault === 1);
        }
      } catch (error) {
        console.error('获取用户地址信息失败:', error);
      }
    },

    // 获取订单信息
    async fetchOrderInfo() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/order/infoidOrderAll`, {
          headers: {
            Authorization: `Bearer ` + localStorage.getItem('token')
          }
        });

        if (response.data.code === 200) {
          const orderData = response.data.data;
          // 遍历订单数据，设置 username
          orderData.forEach(item => {
            item.username = item.username == null || item.username === "" ? "乐购" + (item.addressMobile ? item.addressMobile.slice(-4) : '') : item.username;
          });
          this.dataSource = orderData.reverse();
          this.filteredDataSource = [...orderData];
          this.pagination.total = orderData.length;
          this.updateCounts(this.filteredDataSource)
        } else {
          console.error('获取订单信息失败:', response.data.msg);
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },

    // 点击“查看订单详情”按钮时，显示模态框
    viewDetails(id) {
      const order = this.dataSource.find(item => item.id === id);
      this.selectedOrder = order;
      this.isModalVisible = true;
    },

    // 关闭订单详情模态框
    handleCancel() {
      this.isModalVisible = false;
      this.selectedOrder = null;
    },

    // 关闭发货模态框
    handleShipCancel() {
      this.isShipModalVisible = false;
      this.shipForm.shippingCompany = '';
      this.shipForm.trackingNumber = '';
    },

    // 发货操作
    async shipOrder() {
      try {
        const response = await axios.post(`${window.location.protocol}//${window.location.hostname}:8080/api/order/ship`, {
          orderId: this.selectedOrder.id,
          shippingCompany: this.shipForm.shippingCompany,
          trackingNumber: this.shipForm.trackingNumber,
        }, {
          headers: {
            Authorization: `Bearer ` + localStorage.getItem('token')
          }
        });

        if (response.data.code === 200) {
          this.$message.success('发货成功');
          this.handleShipCancel(); // 关闭发货模态框
          this.fetchOrderInfo(); // 刷新订单列表
        } else {
          this.$message.error('发货失败');
        }
      } catch (error) {
        console.error('发货请求失败:', error);
      }
    },

    // 页码变化时的回调函数
    handlePageChange(page, pageSize) {
      this.pagination.current = page;
      this.pagination.pageSize = pageSize;
      this.fetchOrderInfo(); // 重新加载数据（根据分页重新请求数据）
    },

    filterData() {
      let filtered = [...this.dataSource];

      // 重置计数
      this.unpaidCount = 0;
      this.unfaitCount = 0;
      this.ungiveCount = 0;
      this.unlastCount = 0;
      this.unfalseCount = 0;

      // 根据 defaultActiveKey 进行筛选
      switch (this.defaultActiveKey) {
        case 'selling':
          filtered = filtered.filter(item => item.payIs === '待支付');
          break;
        case 'alert':
          filtered = filtered.filter(item => item.orderStatus === '待发货');
          break;
        case 'warehouse':
          filtered = filtered.filter(item => item.orderStatus === '待收货');
          break;
        case 'lasthouse':
          filtered = filtered.filter(item => item.orderStatus === '已完成');
          break;
        default:
          break;
      }
      this.updateCounts()
      // 可能需要返回过滤后的数据
      this.filteredDataSource = filtered;
    },

    updateCounts() {
      // 统计各个状态的数量
      this.filteredDataSource.forEach(item => {
        if (item.payIs === '待支付') {
          this.unpaidCount++;
        }
        if (item.orderStatus === '待发货') {
          this.unfaitCount++;
        }
        if (item.orderStatus === '待收货') {
          this.ungiveCount++;
        }
        if (item.orderStatus === '已完成') {
          this.unlastCount++;
        }
        // 其他状态统计，可以根据需求添加
      });
    },

    handleChange(activeKey) {
      this.defaultActiveKey = activeKey;
      this.filterData();
    },
  },
};
</script>


<style scoped>
.order-details {
  display: flex;
  justify-content: space-between;
  padding: 20px;
}

.order-image {
  width: 120px;
}

.order-info {
  flex-grow: 1;
  margin-left: 20px;
}

.order-info p {
  margin: 5px 0;
}

.order-info strong {
  width: 120px;
  display: inline-block;
}
</style>